package com.caigou.comm.base.utils

import android.content.Context
import android.graphics.Bitmap
import android.widget.ImageView
import androidx.core.graphics.drawable.RoundedBitmapDrawableFactory
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.BitmapImageViewTarget
import com.caigou.comm.R
import com.luck.picture.lib.engine.ImageEngine
import com.luck.picture.lib.listener.OnImageCompleteCallback
import com.luck.picture.lib.widget.longimage.SubsamplingScaleImageView

/**
 * @author #Suyghur.
 * Created on 2021/11/05
 */
class GlideEngine private constructor() : ImageEngine {
    /**
     * 加载图片
     */
    override fun loadImage(context: Context, url: String, imageView: ImageView) {
        if (!ImageLoader.assertValidRequest(context)) {
            return
        }
        Glide.with(context).load(url).into(imageView)
    }

    /**
     * 加载网络图片适配长图方案
     * 注意：此方法只有加载网络图片才会回调
     */
    override fun loadImage(context: Context, url: String, imageView: ImageView, longImageView: SubsamplingScaleImageView?, callback: OnImageCompleteCallback?) {
    }

    override fun loadImage(context: Context, url: String, imageView: ImageView, longImageView: SubsamplingScaleImageView?) {
    }

    override fun loadFolderImage(context: Context, url: String, imageView: ImageView) {
        if (!ImageLoader.assertValidRequest(context)) {
            return
        }
        Glide.with(context)
            .asBitmap()
            .load(url)
            .override(180, 180)
            .centerCrop()
            .sizeMultiplier(0.5f)
            .placeholder(R.drawable.picture_image_placeholder)
            .into(object : BitmapImageViewTarget(imageView) {
                override fun setResource(resource: Bitmap?) {
                    super.setResource(resource)
                    resource?.apply {
                        val circularBitmapDrawable = RoundedBitmapDrawableFactory.create(context.resources, this)
                        circularBitmapDrawable.cornerRadius = 8f
                        imageView.setImageDrawable(circularBitmapDrawable)
                    }
                }
            })
    }

    override fun loadAsGifImage(context: Context, url: String, imageView: ImageView) {
    }

    /**
     * 加载图片列表图片
     */
    override fun loadGridImage(context: Context, url: String, imageView: ImageView) {
        if (!ImageLoader.assertValidRequest(context)) {
            return
        }
        Glide.with(context)
            .load(url)
            .override(200, 200)
            .centerCrop()
            .placeholder(R.drawable.picture_image_placeholder)
            .into(imageView)
    }

    companion object {
        val instance: GlideEngine by lazy(LazyThreadSafetyMode.SYNCHRONIZED) {
            GlideEngine()
        }
    }
}